﻿using Microsoft.Extensions.Logging;
using PetaPoco;
using PetaPoco.Providers;
using LaserMark.DataAccess.Extensions;
using System.Collections.Specialized;

namespace LaserMark.DataAccess
{
    public class DBManager : IDBManager
    {
        private ILogger<DBManager> Logger { get; set; }

        public DBManager(ILogger<DBManager> logger)
        {
            Logger = logger;
        }

        public IDatabase Create()
        {
            var option = DatabaseConfiguration.Build();
#if DEBUG
            option.UsingConnectionString("Data Source = ..//..//..//Mark.db");
#else
            option.UsingConnectionString("Data Source = Mark.db");
#endif
            option.UsingDefaultMapper<DataBaseMapper>();
            option.UsingProvider<SQLiteDatabaseProvider>();
            var db = new Database(option);

            db.ExceptionThrown += (sender, e) =>
            {
                var message = e.Exception.Format(new NameValueCollection()
                {
                    [nameof(db.LastCommand)] = db.LastCommand,
                    [nameof(db.LastArgs)] = string.Join(",", db.LastArgs)
                });
                Logger.LogError(e.Exception, "{Message}", message);
            };

            return db;
        }
    }
}
